import Ajax from './Ajax.js'
import { ERROR_HTTP_CODE, ERROR_HTTP_CODE_TEXT, ERROR_REQUEST, ERROR_REQUEST_TEXT, ERROR_TIMEOUT, ERROR_TIMEOUT_TEXT, ERROR_ABORT, ERROR_ABORT_TEXT } from './constants.js'

const ajax = (url, options) => {
  // return new Ajax(url, options).getXHR()
  let xhr
  const p = new Promise((reslove, reject) => {
    xhr = new Ajax(url, {
      ...options, ...{
        success(response) {
          reslove(response)
        },
        httpCodeError(status, xhr) {
          reject({
            type: ERROR_HTTP_CODE,
            text: `${ERROR_HTTP_CODE_TEXT}:${status}`,
            xhr
          })
        },
        error(xhr) {
          reject({
            type: ERROR_REQUEST,
            text: `${ERROR_REQUEST_TEXT}`,
            xhr
          })
        },
        abort(xhr) {
          reject({
            type: ERROR_ABORT,
            text: `${ERROR_ABORT_TEXT}`,
            xhr
          })
        },

        timeout(xhr) {
          reject({
            type: ERROR_TIMEOUT,
            text: `${ERROR_TIMEOUT_TEXT}`,
            xhr
          })
        },
      }
    }).getXHR()
  })
  p.xhr = xhr
  p.ERROR_HTTP_CODE = ERROR_HTTP_CODE
  p.ERROR_HTTP_CODE_TEXT = ERROR_HTTP_CODE_TEXT

  p.ERROR_REQUEST = ERROR_REQUEST
  p.ERROR_REQUEST_TEXT = ERROR_REQUEST_TEXT

  p.ERROR_TIMEOUT = ERROR_TIMEOUT
  p.ERROR_TIMEOUT_TEXT = ERROR_TIMEOUT_TEXT

  p.ERROR_ABORT = ERROR_ABORT
  p.ERROR_ABORT_TEXT = ERROR_ABORT_TEXT

  return p
}

const get = (url, options) => {
  return ajax(url, { ...options, method: 'get' })
}

const post = (url, options) => {
  return ajax(url, { ...options, method: 'post' })
}

const getJSON = (url, options) => {
  return ajax(url, { ...options, method: 'get', responseType: 'json', })
}
export { ajax, get, post, getJSON }